package com.zzyl.web.controller.common;

import cn.hutool.captcha.AbstractCaptcha;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.generator.MathGenerator;
import cn.hutool.captcha.generator.RandomGenerator;
import cn.hutool.core.util.ObjectUtil;
import com.google.code.kaptcha.Producer;
import com.zzyl.common.config.RuoYiConfig;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.constant.Constants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.core.redis.RedisCache;
import com.zzyl.common.utils.sign.Base64;
import com.zzyl.common.utils.uuid.IdUtils;
import com.zzyl.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 验证码操作处理
 * 
 * @author ruoyi
 */
@RestController
public class CaptchaController
{
    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Autowired
    private RedisCache redisCache;
    
    @Autowired
    private ISysConfigService configService;
    /**
     * 生成验证码
     */
    /*@GetMapping("/captchaImage")
    public AjaxResult getCode(HttpServletResponse response) throws IOException
    {
        AjaxResult ajax = AjaxResult.success();
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        ajax.put("captchaEnabled", captchaEnabled);
        if (!captchaEnabled)
        {
            return ajax;
        }

        // 保存验证码信息
        String uuid = IdUtils.simpleUUID();
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;

        String capStr = null, code = null;
        BufferedImage image = null;

        // 生成验证码
        String captchaType = RuoYiConfig.getCaptchaType();
        if ("math".equals(captchaType))
        {
            String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        }
        else if ("char".equals(captchaType))
        {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }

        redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try
        {
            ImageIO.write(image, "jpg", os);
        }
        catch (IOException e)
        {
            return AjaxResult.error(e.getMessage());
        }

        ajax.put("uuid", uuid);
        ajax.put("img", Base64.encode(os.toByteArray()));
        return ajax;
    }*/

    @GetMapping("/captchaImage")
    public AjaxResult getCode(HttpServletResponse response) throws IOException {
        // 1、判断验证码开关是否打开
        AjaxResult ajax = AjaxResult.success();
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        ajax.put("captchaEnabled", captchaEnabled);
        if (!captchaEnabled) {
            return ajax;}

        // 2、声明验证码一系列变量
        String uuid = IdUtils.simpleUUID();
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
        String capStr,code = null;
        BufferedImage image = null;
        AbstractCaptcha captcha = null;

        // 3、各个渠道 - 生成验证码
        String captchaType = RuoYiConfig.getCaptchaType();
        switch (captchaType){
            case "math": // 谷歌数学四则运算
                String capText = captchaProducerMath.createText();
                capStr = capText.substring(0, capText.lastIndexOf("@"));
                code = capText.substring(capText.lastIndexOf("@") + 1);
                image = captchaProducerMath.createImage(capStr);
                break;
            case "char":  // 谷歌扭曲字符
                capStr = code = captchaProducer.createText();
                image = captchaProducer.createImage(capStr);
                break;
            case "hutool.line.char":{  // 线段干扰字符
                captcha = CaptchaUtil.createLineCaptcha(300, 100);
                break;
            }
            case "hutool.circle.char": { // 圆圈干扰字符
                captcha = CaptchaUtil.createCircleCaptcha(300, 100, 4, 20);
                break;
            }
            case "hutool.shear.char":{ // 扭曲干扰字符
                captcha = CaptchaUtil.createShearCaptcha(300, 100, 4, 4);
                break;
            }
            case "hutool.random.number":{  // 随机数字
                RandomGenerator randomGenerator = new RandomGenerator("0123456789", 4);
                //线段干扰字符样式
                captcha = CaptchaUtil.createLineCaptcha(300, 100);
                captcha.setGenerator(randomGenerator);
                captcha.createCode();
                break;
            }
            //该四则运算code中为 四则运算表达式本身，后续需借助MathGenerator对表达式进行验签
            case "hutool.math":{ // 四则运算
                captcha = CaptchaUtil.createShearCaptcha(300, 100, 4, 4);
                captcha.setGenerator(new MathGenerator(1));
                captcha.createCode();
                break;
            }
            case "hutool.gif":{  //动图
                captcha = CaptchaUtil.createGifCaptcha(300,100,4);
				/*captcha.setGenerator(new MathGenerator());
				captcha.createCode();*/
                break;
            }
            default:
                break;
        }

        // 4、转换流信息写出
        try {
            if(ObjectUtil.isNotEmpty(captcha)){
                code = captcha.getCode();
                byte[] imageBytes = captcha.getImageBytes();
                ajax.put("img", imageBytes);
            }else{
                // 转换流信息写出
                FastByteArrayOutputStream os = new FastByteArrayOutputStream();
                ImageIO.write(image, "jpg", os);
                String imageBytes = Base64.encode(os.toByteArray());
                ajax.put("img", imageBytes);
            }
        } catch (IOException e) {
            return AjaxResult.error(e.getMessage());
        }

        // 5、将验证码存入Redis，有效期 2 分钟
        redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        ajax.put("uuid", uuid);
        return ajax;
    }
}
